package com.sunwhite.herostore.cmdhandler;

import com.sunwhite.herostore.common.BroadCaster;
import com.sunwhite.herostore.common.GameMsgRecognizer;
import com.sunwhite.herostore.common.UserManager;
import com.sunwhite.herostore.config.mq.MQProducer;
import com.sunwhite.herostore.config.mq.VictorMsg;
import com.sunwhite.herostore.entity.User;
import com.sunwhite.herostore.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 处理用户攻击消息
 */
public class UserAttkCmdHandler implements CmdHandler<GameMsgProtocol.UserAttkCmd> {
    /**
     * 日志对象
     */
    private static final Logger log = LoggerFactory.getLogger(UserAttkCmdHandler.class);
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserAttkCmd msg) {
        if (null==ctx||null==msg){
            return;
        }
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (userId == null) {
            return;
        }
        GameMsgProtocol.UserAttkResult.Builder builder = GameMsgProtocol.UserAttkResult.newBuilder();
        builder.setAttkUserId(userId);
        builder.setTargetUserId(msg.getTargetUserId());
        //构建分发攻击动作的消息
        GameMsgProtocol.UserAttkResult userAttkResult = builder.build();
        BroadCaster.broadCast(userAttkResult);
        //构建掉血效果的消息并分发
        GameMsgProtocol.UserSubtractHpResult.Builder userSubtractHpResultBuilder = GameMsgProtocol.UserSubtractHpResult.newBuilder();
        userSubtractHpResultBuilder.setTargetUserId(msg.getTargetUserId());
        userSubtractHpResultBuilder.setSubtractHp(10);
        GameMsgProtocol.UserSubtractHpResult userSubtractHpResult = userSubtractHpResultBuilder.build();
        BroadCaster.broadCast(userSubtractHpResult);

        User targetUser = UserManager.getUserById(msg.getTargetUserId());
        if (null==targetUser){
            return;
        }
        // 在此打印线程名称
        log.info("当前线程 = {}", Thread.currentThread().getName());


        // 可以根据自己的喜好写,
        // 例如加上装备加成、躲避、格挡、暴击等等...
        // 这些都属于游戏的业务逻辑了!
        int subtractHp = 10;
        targetUser.hp = targetUser.hp - subtractHp;
        if (targetUser.hp<=0){
            //广播用户死亡
           BroadCaster.broadDie(targetUser.userId);

            if (!targetUser.died) {
                // 设置死亡标志
                targetUser.died = true;

                // 发送消息到 MQ
                VictorMsg mqMsg = new VictorMsg();
                mqMsg.winnerId = userId;
                mqMsg.loserId = targetUser.userId;
                MQProducer.sendMsg("Victor", mqMsg);
            }

//           //移除用户
//            UserManager.remove(targetUser.userId);
//
//            //广播用户退出
//            BroadCaster.broadCast(targetUser.userId);
        }

    }
}
